const http = require("http");
import { getEnv, logger } from "./utils";
import { createProxy } from "./proxy";
import { createModules } from "./modules";

export function createServer() {
  const moduels = createModules();
  const proxy = createProxy();
  // 创建HTTP服务器
  const server = http.createServer((req, res) => {
    const route = findMatchingRoute(req.url, moduels);

    if (route) {
    //   logger(`路由请求: ${req.url} -> ${route.target}`);
      proxy.web(req, res, { target: route.target });
    } else {
      res.writeHead(404, { "Content-Type": "text/plain" });
      res.end("未找到路由");
    }
  });

  // 查找匹配的路由
  function findMatchingRoute(url, routes) {
    for (const route of routes) {
      if (url.startsWith(route.path)) {
        return route;
      }
    }
    return null;
  }

  // 启动服务器
  const port = getEnv().APP_PORT || 3000;
  server.listen(port, () => {
    logger(`✅ 网关服务器运行在端口 ${port}`);
  });
}

